package ru.jexp.rcp.supply.beans.d18;

import org.eclipse.core.databinding.observable.value.IObservableValue;
import org.eclipse.jface.databinding.viewers.IViewerObservableSet;
import org.eclipse.jface.databinding.viewers.IViewerObservableValue;
import org.eclipse.jface.databinding.viewers.ViewerProperties;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.FillLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.TreeColumn;

import ru.jexp.rcp.supply.beans.project.dvs.sostavizdelia.TreeSorter;
import ru.jexp.rcp.supply.swtext.IColumnCreator;
import ru.jexp.rcp.supply.swtext.factory.JExpLayoutFactory;

public abstract class LookupTreeView extends LookupView<TreeColumn, TreeViewer>
{

	protected abstract void createColumns(IColumnCreator<TreeColumn, TreeViewer> creator, TreeViewer viewer);
	
	protected abstract void createProviders(TreeViewer viewer);
	
	private TreeViewer viewer;
	private IViewerObservableSet filters;
	private IViewerObservableValue input;
	private IViewerObservableValue postSelection;

	public LookupTreeView(String title, Shell parentShell)
	{
		super(title, parentShell);
	}

	public IViewerObservableSet getFilters()
	{
		return filters;
	}

	@Override
	public IObservableValue getInputElements()
	{
		return input;
	}

	public IViewerObservableValue getPostSelection()
	{
		return postSelection;
	}
	
	@Override
	public void refresh()
	{
		viewer.refresh();
	}

	@Override
	public IObservableValue getChooseElement()
	{
		return getPostSelection();
	}

	@Override
	protected void createControls(Composite parent)
	{
		parent.setLayoutData(JExpLayoutFactory.gdFillBoth());
		viewer = new TreeViewer(parent, SWT.SINGLE | SWT.FULL_SELECTION);
		viewer.getTree().setHeaderVisible(true);
		viewer.getTree().setLinesVisible(true);
		
		viewer.setComparator(new TreeSorter());
		
		initLayouts(parent, viewer);
		
		createColumns(IColumnCreator.TREE, viewer);
		createProviders(viewer);
		
		createObservables();
		
		viewer.addDoubleClickListener(new IDoubleClickListener()
		{
			@Override
			public void doubleClick(DoubleClickEvent event)
			{
				handlers.handle(CHOOSE_EVENT);
			}
		});
	}
	
	protected void initLayouts(Composite parent, TreeViewer viewer)
	{
		parent.setLayout(new FillLayout());
	}
	
	private void createObservables()
	{
		filters = ViewerProperties.filters().observe(viewer);
		input = ViewerProperties.input().observe(viewer);
		postSelection = ViewerProperties.singlePostSelection().observe(viewer);
	}
}
